package org.budo.support.java.security.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author lmw
 */
public class DigestUtil {
    public static String md5Hex(byte[] input) {
        if (null == input) {
            return null;
        }

        return org.apache.commons.codec.digest.DigestUtils.md5Hex(input);
    }

    public static String md5Hex(String input) {
        if (null == input) {
            return null;
        }

        return org.apache.commons.codec.digest.DigestUtils.md5Hex(input);
    }

    public static String md5(String input) {
        MessageDigest md = getMessageDigestInstance("md5");
        byte[] hashBytes = md.digest(input.getBytes());
        return fixedHexString(hashBytes);
    }

    public static MessageDigest getMessageDigestInstance(String algorithm) {
        try {
            return MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String fixedHexString(byte[] hashBytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < hashBytes.length; i++) {
            String hex16 = Integer.toString((hashBytes[i] & 0xff) + 0x100, 16);
            stringBuffer.append(hex16.substring(1));
        }

        return stringBuffer.toString();
    }
}